package com.example.demo.dao;

import com.example.demo.config.error.BizException;
import com.example.demo.entity.*;
import com.example.demo.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: WinstonDeng
 * @Description:
 * @Date: Created in 10:33 2020/4/9
 * @Modified by:
 */
@Repository
public class QuestionnaireDao {
    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionnaireRecordMapper questionnaireRecordMapper;

    @Autowired
    private FlowStepMapper flowStepMapper;

    @Autowired
    private StepMapper stepMapper;

    @Autowired
    private DepartmentStepMapper departmentStepMapper;

    @Autowired
    private FlowMapper flowMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DoctorMapper doctorMapper;

    public Questionnaire getById(long questionnaireId) throws BizException {
        Questionnaire questionnaire = questionnaireMapper.findById(questionnaireId);
        if(questionnaire == null){
            throw new BizException("404", "未找到 questionnaire");
        }
        List<Question> questionList = questionMapper.findByQuestionnaireId(questionnaireId);
        if(questionList == null){
            throw new BizException("404", "未找到 questionList");
        }
        questionnaire.setQuestionList(questionList);
        return questionnaire;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean insertQuestionnaireRecord(long flowStepId, List<Long> questionList, List<String> answerList) throws BizException {
        FlowStep flowStep = flowStepMapper.findById(flowStepId);
        if (flowStep == null){
            throw new BizException("404", "未找到 flowstep");
        }
        Step step = stepMapper.findById(flowStep.getStepId());
        List<Question> originQuestionList = questionMapper.findByQuestionnaireId(step.getQuestionnaireId());
        // check question list
        for(int i=0;i<questionList.size();i++){
            if(questionList.get(i) != originQuestionList.get(i).getId()){
                throw new BizException("417", "question 不匹配");
            }
        }
        String answer = "";
        List<Integer> answerIndex = new ArrayList<>();
        for(int i=0;i<answerList.size();i++){
            answer += answerList.get(i);
            if(i < answerList.size()-1){
                answer += ",";
            }
            try {
                answerIndex.add(Integer.parseInt(answerList.get(i)));
            } catch (NumberFormatException e) {
                throw new BizException("418", "answer 不匹配");
            }
        }
        // 计算问卷分数
        int score = 0;
        int maxScore = 0;
        for (int i = 0; i < originQuestionList.size(); i++) {
            List<Integer> scoreList = originQuestionList.get(i).getAnswerList().getScore();
            score += scoreList.get(answerIndex.get(i));
            maxScore += Collections.max(scoreList);
        }
        QuestionnaireRecord questionnaireRecord = new QuestionnaireRecord();
        questionnaireRecord.setFlowStepId(flowStepId);
        questionnaireRecord.setAnswer(answer);
        // 单个问卷分数计算百分比
        if (maxScore > 0) {
            questionnaireRecord.setScore(score * 100 / maxScore);
        }
        // 更新当前步骤状态
        flowStep.setState(FlowStep.STATE_FINISH);
        flowStepMapper.updateFlowStep(flowStep);
        // todo 这里太复杂了，效率也不高，后续可能通过在flowStep表新增orderNum字段 或者 逻辑放service拼装放dao 改进
        // 更新下一步步骤状态
//        Doctor currentDoctor = doctorMapper.findById(currentFlow.getDoctorId());
//        Department currentDepartment = departmentMapper.findById(currentDoctor.getDepartmentId());
//        int currentStepNum = departmentStepMapper.findByDepartmentIdAndStepId(currentDepartment.getId(),step.getId()).getStepNum();
        List<FlowStep> flowStepList = flowStepMapper.findByFlowId(flowStep.getFlowId());
        for(FlowStep flowStepTemp:flowStepList){
            if(flowStepTemp.getState()==FlowStep.STATE_UNFINISH){
                flowStepTemp.setState(FlowStep.STATE_DOING);
                flowStepMapper.updateFlowStep(flowStepTemp);
                break;
            }
        }
        // 如果可能的话，还要下一步判断是否存在（是否是最后一步） 目前需求不存在这种情况，暂不考虑

        return questionnaireRecordMapper.insertQuestionnaireRecord(questionnaireRecord);
    }

    public Questionnaire getQuestionnaireRecordByFlowStepId(long flowStepId) throws BizException{
        FlowStep flowStep = flowStepMapper.findById(flowStepId);
        if (flowStep == null){
            throw new BizException("404", "未找到 flowstep");
        }
        QuestionnaireRecord questionnaireRecord = questionnaireRecordMapper.findByFlowStepId(flowStepId);
        if (questionnaireRecord == null){
            return null;
        }
        Step step = stepMapper.findById(flowStep.getStepId());
        Questionnaire questionnaire = questionnaireMapper.findById(step.getQuestionnaireId());
        List<Question> questionList = questionMapper.findByQuestionnaireId(questionnaire.getId());
        String[] answerList = questionnaireRecord.getAnswerList();
        for(int i=0;i<questionList.size();i++){
            questionList.get(i).setChoice(answerList[i]);
        }
        questionnaire.setQuestionList(questionList);
        questionnaireRecord.setQuestionnaire(questionnaire);
        return questionnaireRecord.getQuestionnaire();
    }

    public List<Questionnaire> getAllQuestionnaire() throws BizException {
        List<Questionnaire> questionnaires = questionnaireMapper.selectAll();
        for (int i = 0; i < questionnaires.size(); i++) {
            List<Question> questionList = questionMapper.findByQuestionnaireId(questionnaires.get(i).getId());
            questionnaires.get(i).setQuestionList(questionList);
        }
        return questionnaires;
    }

    public Questionnaire addQuestionnaire(String desc) throws BizException {
        Questionnaire questionnaire = new Questionnaire();
        questionnaire.setDesc(desc);
        Long addId = questionnaireMapper.addQuestionnaire(questionnaire);
        return questionnaire;
    }

    public String deleteQuestionnaire(Long questionnaireId) throws BizException {
        questionMapper.deleteByQuestionnaireId(questionnaireId);
        questionnaireMapper.deleteQuestionnaire(questionnaireId);
        return "删除成功";
    }

    public String updateQuestionnaireScore(Long questionnaireId, Integer basic, Integer serious) throws BizException {
        WarningScore warningScore = new WarningScore();
        warningScore.setQuestionnaireId(questionnaireId);
        warningScore.setBasic(basic);
        warningScore.setSerious(serious);
        questionnaireMapper.updateQuestionnaireScore(warningScore);
        return "修改成功";
    }

    public Questionnaire addQuestion(Question question) throws BizException {
        Long addId = questionMapper.addQuestion(question);
        return getById(question.getQuestionnaireId());
    }

    public String deleteQuestion(Long questionId) throws BizException {
        questionMapper.deleteQuestion(questionId);
        return "删除成功";
    }

    public AnswerList getAllAnswer(Long questionId) throws BizException {
        Question question = questionMapper.selectAllAnswer(questionId);
        return question.getAnswerList();
    }

    public AnswerList addAnswer(Long questionId, String answer, Integer score) throws BizException {
        Question question = questionMapper.selectAllAnswer(questionId);
        AnswerList answerList = question.getAnswerList();
        if (answerList.getAnswer() == null || answerList.getScore() == null) {
            answerList.setAnswer(new ArrayList<>());
            answerList.setScore(new ArrayList<>());
        }
        answerList.getAnswer().add(answer);
        answerList.getScore().add(score);
        int addId = questionMapper.updateAnswer(question);
        return answerList;
    }

    public AnswerList deleteAnswer(Long questionId, String answer, Integer score) throws BizException {
        Question question = questionMapper.selectAllAnswer(questionId);
        AnswerList answerList = question.getAnswerList();
        for (int i = answerList.getAnswer().size() - 1; i >= 0; i--) {
            if (answerList.getAnswer().get(i).equals(answer) && answerList.getScore().get(i).equals(score)) {
                answerList.getAnswer().remove(i);
                answerList.getScore().remove(i);
                break;
            }
        }
        int addId = questionMapper.updateAnswer(question);
        return answerList;
    }
}
